package com.itheima.stock.help;

import com.google.common.util.concurrent.RateLimiter;
import com.itheima.stock.enums.CodeEnum;
import com.itheima.stock.response.ResponseResult;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;

@Component
@Aspect
@SuppressWarnings("all")
public class LimitAspect {
    private final RateLimiter rateLimiter;

    public LimitAspect(RateLimiter rateLimiter) {
        this.rateLimiter = rateLimiter;
    }

    @Pointcut(value = "@annotation(com.itheima.stock.annotation.Limiter)")
    public void pt(){}

    @Around(value = "pt()")
    public Object limiter(ProceedingJoinPoint point) throws Throwable{
        boolean flag = rateLimiter.tryAcquire();
        if(flag){
            return point.proceed();
        }else {
            return ResponseResult.error(CodeEnum.OVER_CONCURRENT_NUM);
        }

    }
}
